app.directive('ngFocus', function () {      
        return{
            restrict:'A',
            require:'ngModel',
            link: function (scope, element, attrs,ctrl,$scope) {
                ctrl.$focused = false;
                element.bind('focus', function (evt) {                   
                    scope.$apply(function () {
                        ctrl.$focused = true;
                    });
                }).bind('blur', function () {  
                    scope.params.TenantsPhone = element[0].value;
                    console.log( scope.params.TenantsPhone);
                    scope.$apply(function(){
                        ctrl.$focused = false;
                        
                       // alert('这人有没有判断这这里')
                    })
                })
            }
        }
    })


app.controller('createContractCtrl', function($scope, ngDialog, user, rest, tipService, $window, $location, $rootScope, uiLoad) {

    var data = angular.copy($scope.ngDialogData, {});

    if ($window.localStorage.getItem("houseId")) {
        $scope.houseIdInfo = JSON.parse($window.localStorage.getItem("houseId"));
    }

    $scope.params = {
        houseId: $scope.houseIdInfo.id,
        landlordId: user.get('landlordId'),
        tenants: {},
        LeaseStartTime: "",
        LeaseEndTime: "",
    };
    $scope.houseId = $scope.houseIdInfo.id;
    
    rest.post({
        methodId: '1051',
        data:{
            houseId: $scope.houseId,
        },
        success: function(res) {
            // console.log(res.res.data.isExist);
            if (res.res.data.isExist == 0) {
                $scope.isApply = 1;
                $scope.$apply();
                // $scope.createContract = true;
            }else{
                $scope.isApply = 0;
                $scope.$apply();
            }
        },
        error: function() {

        }
    })

    $scope.user = {
        phone: user.get('phone')
    }
    // console.log($scope.houseId);

    // 用于快速生成合同进行测试
      // $scope.params = {
      //   houseId: $scope.houseIdInfo.id,
      //   landlordId: user.get('landlordId'),
      //   TenantsName: "虫子",
      //   TenantsPhone: "19283746561",
      //   IdCard: "310113197906122116",
      //   tenants: {
      //     bankAccount: "6345234523452345",
      //     tenantBankMobile: "18121245246",
      //     contactName: "毛毛虫",
      //     contactMobile: "19121267326",
      //   },
      //   Rent: 5000,
      //   Deposit: 5500,
      //   PayDay: 16
      // };

    $scope.contactRelationship = {};
    $scope.contactRelationshipList = [{
        name: '父母',
        value: '父母'
    }, {
        name: '兄弟姐妹',
        value: '兄弟姐妹'
    }, {
        name: '同事',
        value: '同事'
    }, {
        name: '同学',
        value: '同学'
    }, {
        name: '朋友',
        value: '朋友'
    }, {
        name: '亲属',
        value: '亲属'
    }, {
        name: '配偶',
        value: '配偶'
    }, {
        name: '其他',
        value: '其他'
    }]

    $scope.payType = { selected: { name: '一月一付', value: 0 } };
    $scope.payTypeList = [{
        name: '一月一付',
        value: 0
    }, {
        name: '二月一付',
        value: 1
    }, {
        name: '三月一付',
        value: 2
    }]

    $scope.payRent = { selected: { name: '0', value: 0 } };
    $scope.payRentList = [{
        name: '0',
        value: 0
    }, {
        name: '1',
        value: 1
    }, {
        name: '2',
        value: 2
    }, {
        name: '3',
        value: 3
    }, {
        name: '4',
        value: 4
    }, {
        name: '5',
        value: 5
    }, {
        name: '6',
        value: 6
    }, {
        name: '7',
        value: 7
    }, {
        name: '8',
        value: 8
    }, {
        name: '9',
        value: 9
    }, {
        name: '10',
        value: 10
    }, {
        name: '11',
        value: 11
    }, {
        name: '12',
        value: 12
    }]

    var getAddCost = function(srcArr) {
        var result = [];
        for (var i = 0; i < srcArr.length; i++) {
            if (srcArr[i]) {
                // {AddCostType:1,Amount:500,payType:1}
                result.push({
                    AddCostType: srcArr[i]._Option1.selected.value,
                    payType: srcArr[i]._Option2.selected.value,
                    Amount: srcArr[i]._Option3
                });
            }
        }
        return result;
    }
   

    $scope.otherExp = [];

    $scope.$watch('params.PayDay', function(newValue, oldValue) { 
        // console.log($scope.params.PayDay)
        if ($scope.params.PayDay>0 && $scope.params.PayDay<=28 ) {
            $scope.powerOff = parseInt($scope.params.PayDay) + 1;
            $scope.lockOff = parseInt($scope.params.PayDay) + 2;
            $scope.mastOff = parseInt($scope.params.PayDay) + 3;
        }else{
            $scope.powerOff = "　";
            $scope.lockOff = "　";
            $scope.mastOff = "　";
        }
    });

    $scope.makeSureConfirm = function() {
        console.log($scope.payType);
        console.log($scope.params);

        if(!$scope.params.TenantsName){
            tipService.show("body", {
                message: "租客姓名必填",
                notice:"danger"
            }, 3);
            return;
        }
        if($scope.params.TenantsPhone.length != 11 || $scope.params.TenantsPhone.charAt(0) != 1){
            tipService.show("body", {
                message: "租客手机号未填写或格式有误",
                notice:"danger"
            }, 3);
            return;
        }
        if(!$scope.params.IdCard){
            tipService.show("body", {
                message: "身份证必填",
                notice:"danger"
            }, 3);
            return;
        }

// 银行预留手机和紧急联系人手机若填写要验证格式
        if ($scope.params.tenants.tenantBankMobile){
            if($scope.params.tenants.tenantBankMobile.length != 11 || $scope.params.tenants.tenantBankMobile.charAt(0) != 1){
                tipService.show("body", {
                    message: "租客银行预留手机号格式有误",
                    notice:"danger"
                }, 3);
                return;
            }
        }
        if ($scope.params.tenants.contactMobile) {
            if($scope.params.tenants.contactMobile.length != 11 || $scope.params.tenants.contactMobile.charAt(0) != 1){
                tipService.show("body", {
                    message: "紧急联系人电话格式有误",
                    notice:"danger"
                }, 3);
                return;
            }
            if($scope.params.TenantsPhone == $scope.params.tenants.contactMobile){
                tipService.show("body", {
                    message: "租客手机号码不能与紧急联系人手机号码相同",
                    notice:"danger"
                }, 3);
                return;
            }
            if($scope.params.tenants.contactMobile == $scope.user.phone){
                tipService.show("body", {
                    message: "紧急联系人手机号码不能与房东手机号码相同",
                    notice:"danger"
                }, 3);
                return;
            }
        }
        if($scope.params.TenantsPhone == $scope.user.phone){
            tipService.show("body", {
                message: "租客手机号码不能与房东手机号码相同",
                notice:"danger"
            }, 3);
            return;
        }
// 租客银行信息紧急联系人不必填
        // if(!$scope.params.tenants.bankAccount){
        //     tipService.show("body", {
        //         message: "租客银行卡号填写错误",
        //         notice:"danger"
        //     }, 3);
        //     return;
        // }
        // if(!$scope.contactRelationship.selected || !$scope.params.tenants.contactName || !$scope.params.tenants.contactMobile){
        //     tipService.show("body", {
        //         message: "紧急联系人信息未填写完全",
        //         notice:"danger"
        //     }, 3);
        //     return;
        // }
        if(!$scope.params.Rent){
            tipService.show("body", {
                message: "租金未填写",
                notice:"danger"
            }, 3);
            return;
        }
        if(!$scope.params.Deposit){
            tipService.show("body", {
                message: "押金未填写",
                notice:"danger"
            }, 3);
            return;
        }
        if(!$scope.params.PayDay){
            tipService.show("body", {
                message: "交租日未填写",
                notice:"danger"
            }, 3);
            return;
        }
        if($scope.params.PayDay<1 || $scope.params.PayDay>28){
            tipService.show("body", {
                message: "交租日填写错误，必须在1日至28日之间",
                notice:"danger"
            }, 3);
            return;
        }
        if ($scope.params.LeaseStartTime == undefined || $scope.params.LeaseEndTime == undefined || $scope.params.FixationStartTime == undefined || $scope.params.FixationEndTime == undefined || $scope.params.NoFixationStartTime == undefined || $scope.params.NoFixationEndTime == undefined) {
            tipService.show("body", {
                message: "日期未填写完全",
                notice:"danger"
            }, 3);
            return;
        }

        if ($scope.params.LeaseStartTime > $scope.params.LeaseEndTime) {
            tipService.show("body", {
                message: "总租期结束日期不能早于起始日期",
                notice:"danger"
            }, 3);
            return;
        }
        if ($scope.params.FixationStartTime > $scope.params.FixationEndTime) {
            tipService.show("body", {
                message: "固定租期结束日期不能早于起始日期",
                notice:"danger"
            }, 3);
            return;
        }
        if ($scope.params.NoFixationStartTime > $scope.params.NoFixationEndTime) {
            tipService.show("body", {
                message: "灵活租期结束日期不能早于起始日期",
                notice:"danger"
            }, 3);
            return;
        }

        $scope.params.TenantsName = $scope.params.TenantsName.replace(/[ 　\[\]\\\/\"\'\-!@#$%^&*(){}<>,.?:;~`_+=]/g, "");
        if ($scope.params.tenants.contactName) {
            $scope.params.tenants.contactName = $scope.params.tenants.contactName.replace(/[ 　\[\]\\\/\"\'\-!@#$%^&*(){}<>,.?:;~`_+=]/g, "");
        }
        $scope.params.AddCost = getAddCost($scope.otherExp);
        $scope.params.RentPayType = $scope.payType.selected ? $scope.payType.selected.value : "";
        $scope.params.payPeriods = $scope.payRent.selected ? $scope.payRent.selected.value : "";
        $scope.params.tenants.contactRelationship = $scope.contactRelationship.selected ? $scope.contactRelationship.selected.value : "";

        $scope.createContractDisabled = true;

        rest.post({
            methodId: '4017',
            data: $scope.params,
            success: function(res) {
                if (res.code == 0) {
                    flag = true;
                    tipService.show("body", {
                        message: "租房合同创建成功,跳转中......"
                    }, 3);

                    $scope.loadQrCode(res.res.data);

                } else {
                    
                    res.res.msg = res.res.msg.replace("租金分期", "房租月付");
                    tipService.show("body", {
                        message: res.res.msg,
                        notice: "danger"
                    }, 3);
                    // $scope.confirm({});
                    $scope.createContractDisabled = false;
                }
           
            },
            error: function() {
                $scope.createContractDisabled = false;
            }
        })
        
    }
    $scope.loadQrCode = function(data) {
        ngDialog.openConfirm({
            template: 'js/module/qrcode/qrcode.html',
            resolve: {
                load: function() {
                    return uiLoad.load(['js/module/qrcode/qrcode.js'])
                },
                deps: ['$ocLazyLoad',
                    function($ocLazyLoad) {
                        return $ocLazyLoad.load('monospaced.qrcode').then(function() {
                            return $ocLazyLoad.load(['js/module/qrcode/qrcode.js'])
                        });
                    }
                ]
            },
            data: {
                contractId: data.id,
                openId: data.openId,
                title: data.info
            },
            scope: $scope,
            width: 600,
            // height: 700
        }).then(function(data) {
            $location.path('/app/houseOwner/list');
        }, function(reason) {
            $location.path('/app/houseOwner/list');
        });
    }

    // $scope.$on('rentTime.start', function(event, data) {
    //     $scope.params.LeaseStartTime = data + " 00:00:00";
    // })
    // $scope.$on('rentTime.end', function(event, data) {
    //     $scope.params.LeaseEndTime = data + " 00:00:00";
    // })
    // $scope.$on('fixedTime.start', function(event, data) {
    //     $scope.params.FixationStartTime = data + " 00:00:00";
    // })
    // $scope.$on('fixedTime.end', function(event, data) {
    //     $scope.params.FixationEndTime = data + " 00:00:00";
    // })
    // $scope.$on('notFixedTime.start', function(event, data) {
    //     $scope.params.NoFixationStartTime = data + " 00:00:00";
    // })
    // $scope.$on('notFixedTime.end', function(event, data) {
    //     $scope.params.NoFixationEndTime = data + " 00:00:00";
    // })
    // $scope.$on('rent.date', function(event, data) {
    //     $scope.rentDate = data;
    // });
    //  $scope.$on('rentStartTime', function(event, data) {
    //     $scope.params.LeaseStartTime1 = parseInt(data);
    // });
    // $scope.$watch('params.PayDay', function(newValue, oldValue) {      
    //     if ($scope.params.PayDay < $scope.params.LeaseStartTime1) {
    //         $scope.rentDate = moment().add(1, 'months').format('YYYY/MM/');
    //     }else if($scope.params.PayDay >= $scope.params.LeaseStartTime1){
    //         $scope.rentDate = moment().format('YYYY/MM/');
    //     }
    // });

    $scope.cancelCreate = function(){
        $location.path('/app/houseOwner/list');
    }

    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "/";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        $scope.currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " ";
        // console.log($scope.currentdate);
    }
    
    getNowFormatDate();

    $("#LeaseStartTime").blur(function(){

        var patt1 = new RegExp(/^(?:(?!0000)[0-9]{4}([-/.]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/.]?)0?2\2(?:29))$/);
        if ($scope.params.LeaseStartTime != undefined) {

            $scope.params.LeaseStartTime = $scope.params.LeaseStartTime.replace(/\./g, '/');
            $scope.params.LeaseStartTime = $scope.params.LeaseStartTime.replace(/-/g, '/');
            if ($scope.params.LeaseStartTime.substr(0,2) != 20) {
                console.log($scope.params.LeaseStartTime)
                $scope.params.LeaseStartTime = "20" +  $scope.params.LeaseStartTime;
            }
            var result = patt1.test($scope.params.LeaseStartTime);
            if (result == true) {
                $scope.dateError1 = 0;
                $scope.params.LeaseStartTime = moment($scope.params.LeaseStartTime).format('YYYY/MM/DD');
                $scope.params.LeaseEndTime = moment($scope.params.LeaseStartTime).add(2, 'years').subtract(1, 'days').format('YYYY/MM/DD');
                $scope.params.FixationStartTime = moment($scope.params.LeaseStartTime).format('YYYY/MM/DD');
                $scope.params.NoFixationEndTime = moment($scope.params.LeaseStartTime).add(2, 'years').subtract(1, 'days').format('YYYY/MM/DD');
            }else if(result==false){
                $scope.params.LeaseEndTime = "";
                $scope.params.FixationStartTime = "";
                $scope.params.NoFixationEndTime = "";
                $scope.dateError1 = 1;
            }
        }else{
            $scope.params.LeaseEndTime = "";
            $scope.params.FixationStartTime = "";
            $scope.params.NoFixationEndTime = "";
        }
        $scope.$apply();
    });

    $("#FixationEndTime").blur(function(){

        var patt2 = new RegExp(/^(?:(?!0000)[0-9]{4}([-/.]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/.]?)0?2\2(?:29))$/);
        if ($scope.params.FixationEndTime != undefined) {
            $scope.params.FixationEndTime = $scope.params.FixationEndTime.replace(/\./g, '/');
            $scope.params.FixationEndTime = $scope.params.FixationEndTime.replace(/-/g, '/');
            if ($scope.params.FixationEndTime.substr(0,2) != 20) {
                $scope.params.FixationEndTime = "20" + $scope.params.FixationEndTime;
            }
            var result2 = patt2.test($scope.params.FixationEndTime);
            if (result2 == true) {
                $scope.dateError2 = 0;
                $scope.params.FixationEndTime = moment($scope.params.FixationEndTime).format('YYYY/MM/DD');
                $scope.params.NoFixationStartTime = moment($scope.params.FixationEndTime).add(1, 'days').format('YYYY/MM/DD');
            }else{
                $scope.params.NoFixationStartTime = "";
                $scope.dateError2 = 1;
            }
        }else{
            $scope.params.NoFixationStartTime = "";
        }
        $scope.$apply();
    });

})

// app.controller('TimeCtrl', function($scope) {
//     $scope.today = function() {
//         $scope.LeaseStartTime = moment().format('YYYY/MM/DD');
//         $scope.LeaseEndTime = moment().add(2, 'years').subtract(1, 'days').format('YYYY/MM/DD');
//         $scope.FixationStartTime = moment().format('YYYY/MM/DD');
//         $scope.FixationEndTime = "";
//         $scope.NoFixationStartTime = "";
//         $scope.NoFixationEndTime = moment().add(2, 'years').subtract(1, 'days').format('YYYY/MM/DD');
//     };

//     $scope.closeAll = function() {
//         $scope.openLeaseBeginDated =
//             $scope.openLeaseEndDated =
//             $scope.openFixationBeginDated =
//             $scope.openFixationEndDated =
//             $scope.openNoFixationBeginDated =
//             $scope.openNoFixationEndDated = false;
//     }

//     $scope.openLeaseBeginDate = function($event) {
//         $event.preventDefault();
//         $event.stopPropagation();
//         $scope.closeAll();
//         $scope.openLeaseBeginDated = true;
//     };
//     $scope.openLeaseEndDate = function($event) {
//         $event.preventDefault();
//         $event.stopPropagation();
//         $scope.closeAll();
//         $scope.openLeaseEndDated = true;
//     };

//     $scope.openFixationBeginDate = function($event) {
//         $event.preventDefault();
//         $event.stopPropagation();
//         $scope.closeAll();
//         $scope.openFixationBeginDated = true;
//     };
//     $scope.openFixationEndDate = function($event) {
//         $event.preventDefault();
//         $event.stopPropagation();
//         $scope.closeAll();
//         $scope.openFixationEndDated = true;
//     };

//     $scope.openNoFixationBeginDate = function($event) {
//         $event.preventDefault();
//         $event.stopPropagation();
//         $scope.closeAll();
//         $scope.openNoFixationBeginDated = true;
//     };
//     $scope.openNoFixationEndDate = function($event) {
//         $event.preventDefault();
//         $event.stopPropagation();
//         $scope.closeAll();
//         $scope.openNoFixationEndDated = true;
//     };

//     $scope.dateOptions = {
//         format: 'yyyy/MM/dd',
//         startingDay: 1,
//         class: 'datepicker'
//     };

//     $scope.format = 'yyyy/MM/dd';

//     $scope.today();
    
//     // $scope.$watch('params.PayDay', function(newValue, oldValue) { 

//     //     if (newValue > 28){
//     //         $scope.params.PayDay = 28;
//     //     }
//     //     if (newValue < 1){
//     //         $scope.params.PayDay = 1;
//     //     }
//     //     if (newValue < 10){
//     //         $scope.params.PayDay2 = "0" + newValue;
//     //         console.log(newValue);
//     //     }else{
//     //         $scope.params.PayDay2 = newValue;
//     //     }
//     // });
    
//     $scope.$watch('LeaseStartTime', function(newValue, oldValue) {
//         if ("[object Date]" === Object.prototype.toString.call(newValue)) {
//             $scope.$emit('rentTime.start', moment(newValue).format('YYYY/MM/DD'))
//             $scope.$emit('rentStartTime', moment(newValue).format('DD'))

//             $scope.$emit('fixedTime.start', moment(newValue).format('YYYY/MM/DD'))
//             $scope.FixationStartTime = moment(newValue).format('YYYY/MM/DD')

//             $scope.$emit('rentTime.end', moment(newValue).add(2, 'years').subtract(1, 'days').format('YYYY/MM/DD'))
//             $scope.LeaseEndTime = moment(newValue).add(2, 'years').subtract(1, 'days').format('YYYY/MM/DD')

//             $scope.$emit('notFixedTime.end', moment(newValue).add(2, 'years').subtract(1, 'days').format('YYYY/MM/DD'))
//             $scope.NoFixationEndTime = moment(newValue).add(2, 'years').subtract(1, 'days').format('YYYY/MM/DD')

//             $scope.$emit('rent.date', moment(newValue).format('YYYY/MM/'))
//             $scope.rentDate = moment(newValue).format('YYYY/MM/')
//         }
//     });
//     $scope.$watch('LeaseEndTime', function(newValue, oldValue) {
//         if ("[object Date]" === Object.prototype.toString.call(newValue)) {
//             $scope.$emit('rentTime.end', moment(newValue).format('YYYY/MM/DD'))

//             $scope.$emit('notFixedTime.end', moment(newValue).format('YYYY/MM/DD'))
//             $scope.NoFixationEndTime = moment(newValue).format('YYYY/MM/DD')
//         }
//     });
//     $scope.$watch('FixationStartTime', function(newValue, oldValue) {
//         if ("[object Date]" === Object.prototype.toString.call(newValue)) {
//             $scope.$emit('fixedTime.start', moment(newValue).format('YYYY/MM/DD'))
//         }
//     });
//     $scope.$watch('FixationEndTime', function(newValue, oldValue) {
//         if ("[object Date]" === Object.prototype.toString.call(newValue)) {
//             $scope.$emit('fixedTime.end', moment(newValue).format('YYYY/MM/DD'))
//             console.log(newValue);
//             // $scope.$emit('notFixedTime.start', moment(newValue).add(1, 'days').format('YYYY/MM/DD'))
//             // $scope.NoFixationStartTime = moment(newValue).add(1, 'days').format('YYYY/MM/DD')
//         }
//     });
//     $scope.confirmDate = function(){
//         if ($scope.FixationEndTime == undefined) {
//             $scope.NoFixationStartTime = "";
//         }else{
//             $scope.NoFixationStartTime = moment($scope.FixationEndTime).add(1, 'days').format('YYYY/MM/DD');
//         }
//     }
//     $scope.$watch('NoFixationStartTime', function(newValue, oldValue) {
//         if ("[object Date]" === Object.prototype.toString.call(newValue)) {
//             $scope.$emit('notFixedTime.start', moment(newValue).format('YYYY/MM/DD'))
//         }
//     });
//     $scope.$watch('NoFixationEndTime', function(newValue, oldValue) {
//         if ("[object Date]" === Object.prototype.toString.call(newValue)) {
//             $scope.$emit('notFixedTime.end', moment(newValue).format('YYYY/MM/DD'))
//         }
//     });
// });